package com.doerit.laptops.service.impl;

import java.util.HashMap;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;
import org.springframework.ui.velocity.VelocityEngineUtils;

import com.doerit.laptops.entity.Staff;
import com.doerit.laptops.service.StaffService;

@Service("emailService")
public class EmailService {

	public static final String EMAIL = "email";

	public static final String EMAIL_FIELD = "email-field";
	public static final String PASSWORD = "pass_word";
	public static final String USERNAME = "username";
	
	public static final String PASSWORD_REQUEST_TEMPLATE = "fogotPassword.vm";
	public static final String PASSWORD_RESET_TEMPLATE ="resetPassword.vm";

	private String senderEmail;
	private String emailSubject;
	private VelocityEngine velocityEngine;
	
	@Autowired private StaffService staffService; 

	private static Logger logger = Logger.getLogger(EmailService.class);

	@Autowired
	private JavaMailSender mailSender;
	

	public String sendEmail(String emailAddress) {
		
		Staff staff = staffService.findStaffByEmail(emailAddress);
		
		if(staff != null && !staff.getEmail().isEmpty()) {
			
			Map<String, String> params = new HashMap<String, String>();
			params.put(EmailService.EMAIL, staff.getEmail());
			params.put(EmailService.PASSWORD, staff.getPassword());
		
			try {
				sendEmail(params, EmailService.PASSWORD_REQUEST_TEMPLATE);
			} catch (Exception e) {
				e.printStackTrace();
				return "error.internet";
			}
	
			return "sucess.email.sent";
	
		} else {
			return "error.email.notfound";
		}
	}
	
	public String sendPasswordResetEmail(String emailAddress) {
		
		Staff staff = staffService.findStaffByEmail(emailAddress);
		
		if(staff != null && !staff.getEmail().isEmpty()) {
			
			Map<String, String> params = new HashMap<String, String>();
			params.put(EmailService.EMAIL, staff.getEmail());
			params.put(EmailService.PASSWORD, staff.getPassword());
		
			try {
				sendEmail(params, EmailService.PASSWORD_RESET_TEMPLATE);
			} catch (Exception e) {
				e.printStackTrace();
				return "error.internet";
			}
	
			return "sucess.email.sent";
	
		} else {
			return "error.email.notfound";
		}
	}
	
	public void sendEmail(final Map<String, String> params,
			final String templateName) throws Exception {

		MimeMessagePreparator preparator = new MimeMessagePreparator() {
			public void prepare(MimeMessage mimeMessage) throws Exception {

				MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
				mimeMessage.setDisposition("inline");

				mimeMessage.setHeader("Content-Transfer-Encoding", "8bit");

				mimeMessage.setHeader("Content-Type",
						"Text/HTML;\tcharset=ISO-2022-JP");
				mimeMessage.setSubject(emailSubject, "UTF-8");
				message.setTo(params.get(EMAIL));
				message.setFrom(senderEmail);

				Map<String, Object> model = new HashMap<String, Object>();
				
				if (params.get(EmailService.PASSWORD) != null) {
					model.put(EmailService.PASSWORD, params.get(EmailService.PASSWORD));
				}
				
				if (params.get(EmailService.USERNAME) != null) {
					model.put(EmailService.USERNAME, params.get(EmailService.USERNAME));
				}

				String text = "";

				text = VelocityEngineUtils.mergeTemplateIntoString(
						velocityEngine, "com/aios/util/".concat(templateName),
						"UTF-8", model);

				mimeMessage.setText(text, "UTF-8");

			}
		};
		try {
			this.mailSender.send(preparator);
		} catch (RuntimeException e) {
			logger.error(e);
			throw new com.doerit.laptops.exception.EmailSendException(
					"Due to invalid email address or internet issue, mail cannot be send.");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public String removeHtml(String text) {
		text = text.replaceAll("\\<.*?>", "");
		text = text.replaceAll("&nbsp;", "");
		text = text.replaceAll("&amp;", "");
		return text;
	}

	public String getSenderEmail() {
		return senderEmail;
	}

	public void setSenderEmail(String senderEmail) {
		this.senderEmail = senderEmail;
	}

	public String getEmailSubject() {
		return emailSubject;
	}

	public void setEmailSubject(String emailSubject) {
		this.emailSubject = emailSubject;
	}

	public VelocityEngine getVelocityEngine() {
		return velocityEngine;
	}

	public void setVelocityEngine(VelocityEngine velocityEngine) {
		this.velocityEngine = velocityEngine;
	}

	public JavaMailSender getMailSender() {
		return mailSender;
	}

	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}
	
}
